<?php
namespace app\mobile\controller;

use think\Cache;
use think\Request;

/**
 * Class WxConfig
 * @package app\mobile\controller    微信js sdk配置
 */
class WxConfig extends BaseController
{

    public function get_token()
    {
        $token = Cache::get('access_token');
        $appId = 'wxfad7142a43ba4835';
        $appSecret = '9ee49a690ce634505474649472047c9a';
        if (!$token) {
            $res = curl_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret);

            $arr = json_decode($res, true);
            if (array_key_exists('access_token',$arr)){
                $token = $arr['access_token'];
                Cache::set('access_token', $token, 3600);
            }else{
                abort(500 , '获取token失败');
            }

        }
        return $token;
    }

    /*
     * 获取js的ticket
     */
    public function get_jsApi_ticket()
    {
        //循环获取ticket,直到取到为止
        do{
            $ticket = Cache::get('wx_ticket');
            if ($ticket) {
                break;
            }
            $token = Cache::get('access_token');
            if (!$token){   //无值则再次设置token
                self::get_token();
            }
            $token = Cache::get('access_token');  //再次获取token
            if (!$token) {
                return false;
                break;
            }
            $url2 = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", $token);
            $res = curl_get_contents($url2);
            $res = json_decode($res, true);
            $ticket = $res['ticket'];
            // 注意：这里需要将获取到的ticket缓存起来（或写到数据库中）
            // ticket和token一样，不能频繁的访问接口来获取，在每次获取后，我们把它保存起来。
            Cache::set('wx_ticket', $ticket, 3600);
        }while(0);
        return $ticket;
    }
    /*
     * 微信sdk的配置参数
     */
    public function sdk_config($url)
    {
        $appId = 'wxfad7142a43ba4835';
        $ticket = self::get_jsApi_ticket();
        if (!$ticket){return ['code'=>0,'message'=>'token获取失败'];}
        //将jsapi_ticket、noncestr、timestamp、分享的url按字母顺序连接起来，进行sha1签名。
        //要分享的url(从http开始，如果有参数，包含参数）
        //noncestr是你设置的任意字符串。timestamp为时间戳。
        $timestamp = time();
        $nonceStr = randStr(16);
        $wxOri = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s",
            $ticket, $nonceStr, $timestamp, $url);
        //整理成签名
        $signature = sha1($wxOri);

        //返回配置信息
        return [
            'debug' =>  true,
            'appId' =>  $appId,
            'timestamp' =>  $timestamp,
            'nonceStr'  =>  $nonceStr,
            'signature' =>  $signature,
        ];
    }

}